<template>
  <div class="app-container">
    <div class="header">
      <el-page-header @back="goBack" :content="pageTitle" />
      <div class="mode-switch" v-if="canEditTeam">
        <el-radio-group v-model="currentMode" @change="handleModeChange">
          <el-radio-button label="student">选择学生队友</el-radio-button>
          <el-radio-button label="teacher">选择教师志愿</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <div class="content-wrapper" v-if="canEditTeam">
      <!-- 左侧学生/教师列表 (3/4) -->
      <div class="left-panel">
        <!-- 学生列表 -->
        <student-list-panel
          v-show="currentMode === 'student'"
          ref="studentListPanelRef"
          :group-id="groupId"
          :group-info="groupInfo"
          :selected-students="selectedStudents"
          :is-edit-mode="userTeamStatus.hasTeam && userTeamStatus.isLeader"
          :original-member-ids="Array.from(originalTeamMemberIds)"
          :current-user-id="userProfile?.student?.studentId"
          @select-student="handleSelectStudent"
          @unselect-student="handleUnselectStudent"
          @view-student="handleViewStudent"
        />
        <!-- 教师列表 -->
        <teacher-list-panel
          v-show="currentMode === 'teacher'"
          :group-info="groupInfo"
          :teacher-list="teacherList"
          :teacher-loading="teacherLoading"
          :selected-teachers="selectedTeachers"
          :user-profile="userProfile"
          @select-teacher="handleSelectTeacher"
          @unselect-teacher="handleUnselectTeacher"
          @view-teacher="handleViewTeacher"
          @select-student="handleSelectStudent"
        />
      </div>

      <!-- 右侧队伍表单 (1/4) -->
      <div class="right-panel">
        <student-team-form-panel
          ref="teamFormPanelRef"
          :selected-students="selectedStudents"
          :selected-teachers="selectedTeachers"
          :group-info="groupInfo"
          :submitting="submitting"
          :is-edit-mode="userTeamStatus.hasTeam && userTeamStatus.isLeader"
          @unselect-student="handleUnselectStudent"
          @unselect-teacher="handleUnselectTeacher"
          @submit="handleSubmit"
        />
      </div>
    </div>

    <!-- 学生详情弹窗 -->
    <student-detail-dialog ref="studentDetailDialogRef" />
    <!-- 教师详情弹窗 -->
    <teacher-detail-dialog ref="teacherDetailDialogRef" />

    <!-- 截止时间已过提示 -->
    <div v-show="isDeadlinePassed" class="no-permission-container">
      <el-empty description="志愿填报已结束">
        <template #image>
          <el-icon size="64" color="#cccccc">
            <Clock />
          </el-icon>
        </template>
        <template #description>
          <div class="permission-text">
            <p>志愿填报已结束，无法更改</p>
          </div>
        </template>
        <el-button type="primary" @click="goBack">返回</el-button>
      </el-empty>
    </div>

    <!-- 非队长权限提示 -->
    <div v-show="!canEditTeam && userTeamStatus.hasTeam && !isDeadlinePassed" class="no-permission-container">
      <el-empty description="您不是队长">
        <template #image>
          <el-icon size="64" color="#cccccc">
            <UserFilled />
          </el-icon>
        </template>
        <template #description>
          <div class="permission-text">
            <p>您不是队长，请联系队长修改队伍信息</p>
          </div>
        </template>
        <el-button type="primary" @click="goBack">返回</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, computed, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { getGroupTeachers, getGroup } from '@/api/group'
import { addTeam, updateTeam } from '@/api/team'
import { UserFilled, Clock } from '@element-plus/icons-vue'
import StudentListPanel from './components/StudentListPanel.vue'
import TeacherListPanel from './components/TeacherListPanel.vue'
import StudentTeamFormPanel from './components/StudentTeamFormPanel.vue'
import StudentDetailDialog from '@/views/team/components/StudentDetailDialog.vue'
import TeacherDetailDialog from './components/TeacherDetailDialog.vue'
import { getUserProfile } from '@/api/system/user'

const router = useRouter()
const { proxy } = getCurrentInstance()

// 当前显示模式
const currentMode = ref('student')

// 用户信息
const userProfile = ref({})

// 用户队伍状态
const userTeamStatus = computed(() => {
  const studentTeam = userProfile.value?.student?.studentTeam
  if (!studentTeam) {
    return { hasTeam: false, isLeader: false, team: null }
  }

  const isLeader = studentTeam?.team?.studentTeams?.some(s => s.isLeader === '1' && s.studentId === userProfile.value?.student?.studentId)

  return {
    hasTeam: true,
    isLeader,
    team: studentTeam
  }
})

// 是否已截止
const isDeadlinePassed = computed(() => {
  if (!groupInfo.value.endTime) return false
  return new Date(groupInfo.value.endTime) < new Date()
})

// 是否可以编辑队伍
const canEditTeam = computed(() => {
  // 如果已截止，不允许编辑
  if (isDeadlinePassed.value) return false
  // 如果没有队伍或者是队长，允许编辑
  return !userTeamStatus.value.hasTeam || userTeamStatus.value.isLeader
})

// 页面标题
const pageTitle = computed(() => {
  if (userTeamStatus.value.hasTeam && userTeamStatus.value.isLeader) {
    return '修改队伍信息'
  }
  return '创建队伍'
})

// 分组ID
const groupId = computed(() => userProfile.value?.student?.major?.groupId)

// 分组信息
const groupInfo = ref({
  groupName: '',
  teamMax: 0,
  teacherMax: 0,
  teacherMin: 1,
  endTime: null
})

// 已选学生
const selectedStudents = ref([])

// 已选教师
const selectedTeachers = ref([])

// 教师列表
const teacherLoading = ref(false)
const teacherList = ref([])

// 提交状态
const submitting = ref(false)

// 组件引用
const studentListPanelRef = ref(null)
const teamFormPanelRef = ref(null)
const studentDetailDialogRef = ref(null)
const teacherDetailDialogRef = ref(null)

// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await getUserProfile()
    if (res && res.data) {
      userProfile.value = res.data.data
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    proxy.$modal.msgError('获取用户信息失败')
  }
}

// 获取分组详情
const getGroupInfo = async () => {
  if (!groupId.value) return
console.log(groupId.value)
  try {
    const res = await getGroup(groupId.value)
    if (res && res.data) {
      groupInfo.value = {
        groupName: res.data.groupName || '',
        teamMax: res.data.teamMax || 0,
        teacherMax: res.data.teacherMax || 0,
        teacherMin: res.data.teacherMin || 1,
        endTime: res.data.endTime || null
      }
    }
  } catch (error) {
    console.error('获取分组详情失败:', error)
    proxy.$modal.msgError('获取分组详情失败')
  }
}

// 获取教师列表
const getTeacherList = async () => {
  if (!groupId.value) return

  teacherLoading.value = true
  try {
    const res = await getGroupTeachers(groupId.value)
    if (res && res.data) {
      teacherList.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取教师列表失败:', error)
    teacherList.value = []
  } finally {
    teacherLoading.value = false
  }
}

// 切换显示模式
const handleModeChange = (mode) => {
  currentMode.value = mode
}

// 存储原始队伍成员ID集合（用于编辑模式判断）
const originalTeamMemberIds = ref(new Set())

// 初始化时保存原始队伍成员
watch(userProfile, () => {
  if (userTeamStatus.value.hasTeam && userTeamStatus.value.isLeader) {
    const students = userTeamStatus.value.team?.team?.studentTeams || []
    console.log('初始化原始队伍成员:')
    console.log('学生列表:', students)
    const studentIds = students.map(s => s.studentId)
    console.log('学生ID列表:', studentIds)
    originalTeamMemberIds.value = new Set(studentIds)
    console.log('原始成员ID集合已设置')
  } else {
    originalTeamMemberIds.value.clear()
    console.log('清空原始成员ID集合')
  }
}, { immediate: true, deep: true })

// 选择学生
const handleSelectStudent = (student) => {
  const currentUserId = userProfile.value?.student?.studentId

  // 在编辑模式下，如果是原始队伍成员或当前用户，允许重新选择
  const isOriginalTeamMember = originalTeamMemberIds.value.has(student.studentId)
  const isCurrentUser = student.studentId === currentUserId

  // 调试信息
  console.log('选择学生 - 调试信息:')
  console.log('学生ID:', student.studentId)
  console.log('学生姓名:', student.studentName || student.user?.nickName)
  console.log('学生组队状态:', student.studentTeam)
  console.log('原始成员:', isOriginalTeamMember)
  console.log('是当前用户:', isCurrentUser)
  console.log('是否有队伍:', userTeamStatus.value.hasTeam)
  console.log('原始成员ID列表:', Array.from(originalTeamMemberIds.value))

  // 检查是否已组队（编辑模式下，原始队伍成员和当前用户可以重新选择）
  if (!userTeamStatus.value.hasTeam && student.studentTeam !== null) {
    proxy.$modal.msgWarning('该学生已组队，无法选择')
    return
  }

  // 在编辑模式下检查组队状态
  // 允许原始队伍成员和当前用户重新选择，即使他们的studentTeam不为空
  if (userTeamStatus.value.hasTeam && student.studentTeam !== null && !isOriginalTeamMember && !isCurrentUser) {
    console.log('阻止选择 - 非原始成员且非当前用户')
    proxy.$modal.msgWarning('该学生已组队，无法选择')
    return
  }

  // 检查是否超过队伍人数上限（编辑模式下不检查）
  const teamMax = groupInfo.value.teamMax || 0
  if (!userTeamStatus.value.hasTeam && teamMax > 0 && selectedStudents.value.length >= teamMax) {
    proxy.$modal.msgWarning(`队伍人数不能超过 ${teamMax} 人`)
    return
  }

  // 检查是否已经选择
  const existingIndex = selectedStudents.value.findIndex((s) => s.studentId === student.studentId)
  if (existingIndex === -1) {
    selectedStudents.value.push(student)
    console.log('成功添加学生到队伍')
    console.log('当前队伍成员:', selectedStudents.value.map(s => s.studentId))
  } else {
    console.log('学生已存在于当前队伍中')
  }
}

// 取消选择学生
const handleUnselectStudent = (studentId) => {
  const index = selectedStudents.value.findIndex((s) => s.studentId === studentId)
  if (index !== -1) {
    // 队长不能取消选择（所有模式）
    if (studentId === userProfile.value?.student?.studentId) {
      proxy.$modal.msgWarning('队长不能取消选择')
      return
    }

    console.log('移除学生:', studentId)
    selectedStudents.value.splice(index, 1)
    console.log('移除后的队伍:', selectedStudents.value.map(s => s.studentId))
  }
}

// 选择教师志愿
const handleSelectTeacher = ({ teacher, volunteerOrder }) => {
  if (!selectedTeachers.value.some((t) => t.teacherId === teacher.teacherId)) {
    selectedTeachers.value.push({
      ...teacher,
      volunteerOrder
    })
    // 按志愿顺序排序
    selectedTeachers.value.sort((a, b) => a.volunteerOrder - b.volunteerOrder)
  }
}

// 取消选择教师
const handleUnselectTeacher = (teacherId) => {
  const index = selectedTeachers.value.findIndex((t) => t.teacherId === teacherId)
  if (index !== -1) {
    selectedTeachers.value.splice(index, 1)
    // 重新排序
    selectedTeachers.value.forEach((teacher, idx) => {
      teacher.volunteerOrder = idx + 1
    })
  }
}

// 查看学生详情
const handleViewStudent = (student) => {
  if (!studentDetailDialogRef.value) {
    console.warn('学生详情弹窗组件未加载')
    return
  }
  studentDetailDialogRef.value.openDialog(student)
}

// 查看教师详情
const handleViewTeacher = (teacher) => {
  if (!teacherDetailDialogRef.value) {
    console.warn('教师详情弹窗组件未加载')
    return
  }
  teacherDetailDialogRef.value.openDialog(teacher)
}

// 提交表单
const handleSubmit = async (payload) => {
  if (submitting.value) return
  submitting.value = true

  try {
    // 添加分组ID等必要信息，并将教师志愿转成逗号分隔字符串
    let submitData = {
      ...payload,
      groupId: groupId.value,
      deptId: userProfile.value.student?.major?.deptId,
      gradeId: userProfile.value.student?.major?.gradeId,
      teacherVolunteers: selectedTeachers.value.map(t => t.teacherId).join(',')
    }

    if (userTeamStatus.value.hasTeam && userTeamStatus.value.isLeader) {
      // 编辑模式：更新队伍
      submitData.teamId = userTeamStatus.value.team.teamId
      await updateTeam(submitData)
      proxy.$modal.msgSuccess('更新队伍成功')
    } else {
      // 创建模式：创建新队伍
      await addTeam(submitData)
      proxy.$modal.msgSuccess('创建队伍成功')
    }

    // 返回上一页
    goBack()
  } catch (error) {
    console.error('创建队伍失败:', error)
    if (error.message) {
      proxy.$modal.msgError(error.message)
    }
  } finally {
    submitting.value = false
  }
}

// 返回
const goBack = () => {
  router.back()
}

// 加载或初始化队伍数据
const loadOrCreateTeamData = () => {
  if (userTeamStatus.value.hasTeam && userTeamStatus.value.isLeader) {
    // 编辑模式：加载现有队伍数据
    const teamData = userTeamStatus.value.team.team || {}
    console.log('teamData:', teamData)
    // 确保学生数据完整性
    const students = teamData?.studentTeams || []
    selectedStudents.value = students.map(s => ({
      ...s.student,
      isLeader: s.isLeader
    }))

    selectedTeachers.value = teamData?.teamTeachers.sort((a, b) => a.sort - b.sort).map(t => ({
      ...t.teacher,
      sort: t.sort
    })) || []

    // 设置队伍表单数据
    nextTick(() => {
      if (teamFormPanelRef.value) {
        teamFormPanelRef.value.teamForm.teamName = teamData?.teamName || ''
        teamFormPanelRef.value.teamForm.summary = teamData?.summary || ''
        teamFormPanelRef.value.teamForm.teamLink = teamData?.teamLink || ''

        // 设置队长ID
        const leader = selectedStudents.value.find(s => s.isLeader === '1')
        if (leader) {
          teamFormPanelRef.value.teamForm.leaderId = leader.studentId
        }
      }
    })
  } else if (!userTeamStatus.value.hasTeam) {
    // 创建模式：自动添加当前用户为队长
    setTimeout(() => {
      if (userProfile.value?.student) {
        handleSelectStudent(userProfile.value.student)
      }
    }, 100)
  }
}

// 自动设置当前用户为队长（仅在创建模式下）
watch([selectedStudents, userProfile], () => {
  if (!userTeamStatus.value.hasTeam) {
    const currentUserId = userProfile.value?.student?.studentId
    if (currentUserId && selectedStudents.value.length > 0) {
      const currentUser = selectedStudents.value.find(s => s.studentId === currentUserId)
      if (currentUser && teamFormPanelRef.value && teamFormPanelRef.value.teamForm) {
        teamFormPanelRef.value.teamForm.leaderId = currentUserId
      }
    }
  }
}, { immediate: true, deep: true })

// 监听用户信息变化，加载队伍数据
watch(userProfile, () => {
  if (userProfile.value) {
    loadOrCreateTeamData()
  }
}, { immediate: true, deep: true })

// 初始化
onMounted(async () => {
  try {
    // 获取用户信息
    await getUserInfo()

    // 先获取分组详情
    await getGroupInfo()

    // 获取教师列表
    await getTeacherList()
  } catch (error) {
    console.error('页面初始化失败:', error)
    proxy.$modal.msgError('页面初始化失败')
    goBack()
  }
})
</script>

<style scoped>
.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mode-switch {
  flex-shrink: 0;
}

.content-wrapper {
  display: flex;
  height: calc(100dvh - 164px);
  width: 100%;
  gap: 20px;
  align-items: flex-start;
}

.left-panel {
  width: 75%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.right-panel {
  width: 25%;
  height: 100%;
}

.no-permission-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  z-index: 1000;
}

.permission-text {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.permission-text p {
  margin: 0 0 10px 0;
}
</style>
